using Circus.CodeEditor.Serialization;
using Circus.CodeEditor.TextSource;
using Circus.Syntax;
using Circus.Syntax.Lexer;
using System;
using System.ComponentModel;
using System.Drawing;
using System.IO;
namespace Circus.CodeEditor.CodeCompletion
{
	[DesignerCategory("Code")]
	public class HtmlLexer : Lexer
	{
		private class HtmlItem : StringItem
		{
			public HtmlItem(string s) : base(s)
			{
			}
			public void Add(string text, StringItemInfo style)
			{
				int num = this.TextData.Length;
				StringItemInfo[] array = new StringItemInfo[num + text.Length];
				if (num > 0)
				{
					this.TextData.CopyTo(array, 0);
				}
				this.String += text;
				for (int i = 0; i < text.Length; i++)
				{
					array[num + i] = style;
				}
				this.TextData = array;
			}
		}
		private FmtImport importer;
		protected byte GetStyle(Color foreColor, Color backColor, FontStyle fontStyle)
		{
			byte result;
			foreach (LexStyle current in this.Scheme.Styles)
			{
				if (current.ForeColor == foreColor && current.BackColor == backColor && current.FontStyle == fontStyle)
				{
					result = (byte)(current.Index + 1);
					return result;
				}
			}
			LexStyle lexStyle = this.Scheme.Styles.AddLexStyle();
			lexStyle.ForeColor = foreColor;
			lexStyle.BackColor = backColor;
			lexStyle.FontStyle = fontStyle;
			result = (byte)(lexStyle.Index + 1);
			return result;
		}
		protected void ReadFormattedText(object sender, ReadFormattedTextEventArgs e)
		{
			StringItemInfo style = default(StringItemInfo);
			style.Data = this.GetStyle(e.ForeColor, e.BackColor, e.FontStyle);
			if (e.UserData is HtmlLexer.HtmlItem)
			{
				((HtmlLexer.HtmlItem)e.UserData).Add(e.Text, style);
			}
		}
		public HtmlLexer()
		{
			this.importer = new HtmlImporter();
			this.importer.ReadFormattedText += new ReadFormattedTextEvent(this.ReadFormattedText);
		}
		public int ParseHtmlText(int state, FontStyle style, ref string s, ref StringItemInfo[] colorData)
		{
			StringReader reader = new StringReader(s);
			HtmlLexer.HtmlItem htmlItem = new HtmlLexer.HtmlItem(string.Empty);
			this.importer.DefaultStyle = style;
			this.importer.BeginRead(reader, htmlItem);
			try
			{
				this.importer.Read();
			}
			finally
			{
				this.importer.EndRead();
			}
			s = htmlItem.String;
			colorData = htmlItem.TextData;
			return state;
		}
		protected override void Dispose(bool disposing)
		{
			if (disposing)
			{
				if (this.importer != null)
				{
					this.importer.ReadFormattedText -= new ReadFormattedTextEvent(this.ReadFormattedText);
					this.importer.Dispose();
					this.importer = null;
				}
			}
			base.Dispose(disposing);
		}
	}
}
